import {
    chat,
    getChatMemory,
    getChatConversation,
    stopAnswer,
    deleteConversation
} from '../../utils/api'

Page({
    data: {
        // websocket对象
        socketTask: '',
        messages: [],
        inputValue: '',
        // 正在思考
        isTyping: false,
        scrollTop: 0,
        // 当前回复消息
        currentAssistantMessage: '',
        socketOpen: false,
        // 正在回答
        answering: false,
        // 发送图标
        sendIconImageUrl: '/images/cant-not-send-icon.png',
        // 展示顶部波纹
        showWave: true,
        chatHistoryDialog: false,
        openTyper: false,
        // 聊天对话
        conversations: [],
        // 当前会话ID
        conversationId: ''
    },

    onLoad() {
        this.initChat()
    },

    onShow() {
        if (!this.data.socketOpen) {
            setTimeout(() => {
                this.initWebSocket()
            }, 1000);
        }
    },

    onClose() {
        this.data.socketTask.close()
    },

    onHide() {
        this.data.socketTask.close()
    },

    /**
     * 初始化websocket
     */
    initWebSocket() {
        // 获取websocket连接
        const socketTask = wx.connectSocket({
            url: 'wss://dataling.cn/ai-lawyer/websocket/' + wx.getStorageSync('openId'),
            header: {
                openId: wx.getStorageSync('openId')
            }
        })

        // websocket连接成功之后执行
        socketTask.onOpen(res => {
            wx.showToast({
                title: '服务端连接成功',
                icon: 'success'
            })
            this.setData({
                socketTask: socketTask,
                socketOpen: true,
            })
            //this.sendHeart()
        })

        // websocket连接失败之后执行
        socketTask.onError(res => {
            wx.showToast({
                title: '服务端连接失败',
                icon: 'fail'
            })
        })

        // 接收到消息之后执行
        socketTask.onMessage(res => {
            const data = res.data
            if (data != "200") {
                this.processStreamResponse(data)
            }
        })

        // 连接关闭时执行
        socketTask.onClose(res => {
            this.setData({
                socketOpen: false
            })
        })
    },

    /**
     * 发送消息
     */
    sendMessage() {
        const text = this.data.inputValue.trim();
        if (!text) return;

        // 添加用户消息
        this.addMessage({
            role: 'USER',
            text: text,
            time: this.formatTime(new Date())
        });

        this.setData({
            inputValue: '',
            isTyping: true,
            answering: true,
            sendIconImageUrl: '/images/answering.png',
            openTyper: true
        });

        // 滚动到底部
        this.scrollToBottom();

        // 延时发送websocket
        setTimeout(() => {
            chat({
                openId: wx.getStorageSync('openId'),
                message: text,
                conversationId: this.data.conversationId
            })
        }, 500);
    },

    /**
     * 停止回答
     */
    stopAnswer() {
        stopAnswer({
            openId: wx.getStorageSync('openId')
        }).then(res => {
            wx.showToast({
                title: '停止成功',
            })
        })
    },

    /**
     * 处理流式数据
     * @param {*} data 
     */
    processStreamResponse(data) {
        switch (data) {
            case '[start]':
                this.setData({
                    answering: true,
                    isTyping: false,
                });
                this.addMessage({
                    role: 'ASSISTANT',
                    text: this.data.currentAssistantMessage,
                    time: this.formatTime(new Date())
                });
                break;
            case '[end]':
                this.setData({
                    currentAssistantMessage: '',
                    answering: false,
                    sendIconImageUrl: '/images/cant-not-send-icon.png'
                });
                break;
            default:
                // 更新当前消息
                this.setData({
                    currentAssistantMessage: this.data.currentAssistantMessage + data
                });
                let i = this.data.messages.length - 1
                this.setData({
                    [`messages[${i}].text`]: this.data.currentAssistantMessage,
                })
                break;
        }
        this.scrollToBottom();
    },

    onInput(e) {
        this.setData({
            inputValue: e.detail.value,
            sendIconImageUrl: e.detail.value ? '/images/send-icon.png' : '/images/cant-not-send-icon.png'
        });
    },

    /**
     * 添加消息
     * @param {*} message 
     */
    addMessage(message) {
        const newMessage = {
            ...message,
            id: Date.now()
        };
        this.setData({
            messages: [...this.data.messages, newMessage]
        });
        this.scrollToBottom();
    },

    /**
     * 发送心跳
     */
    sendHeart() {
        setInterval(() => {
            if (this.data.socketOpen) {
                this.data.socketTask.send({
                    data: "100"
                })
            }
        }, 10000);
    },

    /**
     * 查询聊天会话
     */
    getChatConversation() {
        getChatConversation({
            openId: wx.getStorageSync('openId')
        }).then(res => {
            this.setData({
                conversations: res.data,
                chatHistoryDialog: true
            })
        })
    },

    /**
     * 打开历史对话
     */
    openChatHistory(e) {
        getChatMemory({
            conversationId: e.currentTarget.dataset.index
        }).then(res => {
            const messages = res.data.map(item => {
                let message = {
                    role: item.type,
                    text: item.content,
                    time: item.createdAt
                }
                return message
            })

            this.setData({
                messages: messages,
                chatHistoryDialog: false,
                conversationId: e.currentTarget.dataset.index,
                openTyper: false
            });
            this.scrollToBottom();
        })
    },

    /**
     * 删除聊天会话
     */
    deleteConversation(e) {
        wx.showModal({
            content: '确定删除吗？',
            complete: (res) => {
                if (res.confirm) {
                    deleteConversation({
                        id: e.detail.data
                    }).then(res => {
                        if (res.data > 0) {
                            this.getChatConversation()
                            wx.showToast({
                                title: '操作成功'
                            })
                        }
                    })
                }
            }
        })
    },

    /**
     * 生成UUID
     */
    generateUUID() {
        const timestamp = Date.now().toString(16);
        const random = Math.random().toString(16).slice(2);
        return `${timestamp}-${random}`;
    },

    /**
     * 初始化聊天
     */
    initChat() {
        // 初始化欢迎消息
        this.setData({
            conversationId: this.generateUUID(),
            messages: [],
            currentAssistantMessage: ''
        })
        this.addMessage({
            role: 'ASSISTANT',
            text: '您好，我是AI律师助手。我可以为您解答法律问题，提供法律咨询。请问您有什么法律问题需要帮助？',
            time: this.formatTime(new Date())
        });
    },

    /**
     * 设置滚动向底部
     */
    scrollToBottom() {
        this.setData({
            scrollTop: 99999
        });
    },

    /**
     * 时间格式化
     * @param {*} date 
     */
    formatTime(date) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}`;
    }
});